import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:wanzhende_app/common/utils/level_util.dart';
import 'package:wanzhende_app/common/widgets/cached_image.dart';
import 'package:wanzhende_app/common/models/index.dart'; // 🔥 导入模型类
import 'index.dart';

/// 消息/好友列表页面视图
/// 
/// 显示用户的好友列表和好友申请列表，支持下拉刷新
class MessageIndexPage extends GetView<MessageIndexController> {
  const MessageIndexPage({super.key});

  // 主视图
  Widget _buildView() {
    return Column(
      children: [
        // TabBar
        _buildTabBar(),
        
        // TabBarView（🔥 禁止左右滑动）
        Expanded(
          child: TabBarView(
            controller: controller.tabController,
            physics: const NeverScrollableScrollPhysics(), // 🔥 禁止左右滑动
            children: [
              // 🔥 好友消息列表（新增：显示最后一条消息和未读数）
              _buildFriendMessageListTab(),
              
              // 好友申请列表
              _buildFriendRequestListTab(),
              
              // 🔥 活动申请列表
              _buildActivityApplicationListTab(),
            ],
          ),
        ),
      ],
    );
  }
  
  /// 构建 TabBar
  Widget _buildTabBar() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Obx(() => TabBar(
        controller: controller.tabController,
        tabs: [
          // 🔥 第一个标签：好友消息（显示未读数）
          Tab(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text('好友消息'),
                if (controller.friendMessageList.any((item) => item.unreadCount > 0))
                  Text(
                    controller.formatMessageCount(
                      controller.friendMessageList.fold<int>(0, (sum, item) => sum + item.unreadCount)
                    ),
                    style: const TextStyle(fontSize: 14),
                  ),
              ],
            ),
          ),
          
          // 🔥 第二个标签：好友申请（显示申请数量）
          Tab(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text('好友申请'),
                if (controller.friendRequestCount > 0)
                  Text(
                    controller.formatMessageCount(controller.friendRequestCount),
                    style: const TextStyle(fontSize: 14),
                  ),
              ],
            ),
          ),
          
          // 🔥 第三个标签：活动申请（显示申请数量）
          Tab(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text('活动申请'),
                if (controller.activityApplicationCount > 0)
                  Text(
                    controller.formatMessageCount(controller.activityApplicationCount),
                    style: const TextStyle(fontSize: 14),
                  ),
              ],
            ),
          ),
        ],
        labelColor: const Color(0xFFFF6B6B),
        unselectedLabelColor: Colors.grey[600],
        indicatorColor: const Color(0xFFFF6B6B),
        indicatorWeight: 3,
        labelStyle: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w600,
        ),
        unselectedLabelStyle: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.normal,
        ),
      )),
    );
  }
  
  /// 🔥 构建好友消息列表 Tab（新增：显示最后一条消息和未读数）
  Widget _buildFriendMessageListTab() {
    return Obx(() {
      // 空状态
      if (controller.friendMessageList.isEmpty) {
        return RefreshIndicator(
          onRefresh: controller.refreshFriendMessageList,
          child: ListView(
            physics: const AlwaysScrollableScrollPhysics(),
            children: [
              SizedBox(
                height: MediaQuery.of(Get.context!).size.height * 0.6,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.chat_bubble_outline,
                        size: 64,
                        color: Colors.grey[400],
                      ),
                      const SizedBox(height: 16),
                      Text(
                        '暂无消息',
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 16,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '下拉可刷新消息列表',
                        style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      }
      
      // 🎨 好友消息列表
      return RefreshIndicator(
        onRefresh: controller.refreshFriendMessageList,
        child: ListView.builder(
          padding: const EdgeInsets.symmetric(vertical: 4),
          itemCount: controller.friendMessageList.length,
          itemBuilder: (context, index) {
            final item = controller.friendMessageList[index];
            return _buildFriendMessageItem(item);
          },
        ),
      );
    });
  }
  
  /// 🎨 构建好友消息列表项（微信式：显示最后一条消息和未读数）
  Widget _buildFriendMessageItem(item) {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => controller.onFriendMessageTap(item),
          onLongPress: () => controller.onFriendMessageLongPress(item),
          borderRadius: BorderRadius.circular(12),
          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Row(
              children: [
                // 🎨 头像（带未读红点）
                Stack(
                  children: [
                    CircleAvatar(
                      radius: 28,
                      backgroundColor: Colors.grey[200],
                      backgroundImage: item.friendAvatar.isNotEmpty 
                          ? CachedNetworkImageProvider(item.friendAvatar)
                          : null,
                      child: item.friendAvatar.isEmpty 
                          ? Icon(Icons.person, size: 32, color: Colors.grey[400])
                          : null,
                    ),
                    // 🔥 未读红点
                    if (item.unreadCount > 0)
                      Positioned(
                        top: 0,
                        right: 0,
                        child: Container(
                          padding: const EdgeInsets.all(4),
                          decoration: const BoxDecoration(
                            color: Color(0xFFFF3B30),
                            shape: BoxShape.circle,
                            boxShadow: [
                              BoxShadow(
                                color: Colors.white,
                                blurRadius: 0,
                                spreadRadius: 2,
                              ),
                            ],
                          ),
                          constraints: const BoxConstraints(
                            minWidth: 18,
                            minHeight: 18,
                          ),
                          child: Center(
                            child: Text(
                              item.unreadCount > 99 ? '99+' : '${item.unreadCount}',
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 10,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                      ),
                  ],
                ),
                const SizedBox(width: 12),
                
                // 🎨 信息区域
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 昵称 + 时间
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              item.friendName,
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                                color: Color(0xFF333333),
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          // 🔥 只有当有消息时才显示时间
                          if (item.formattedTime.isNotEmpty) ...[
                            const SizedBox(width: 8),
                            Text(
                              item.formattedTime,
                              key: ValueKey('time_${item.friendId}_${item.lastMessageTime}'), // 强制更新
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[500],
                              ),
                            ),
                          ],
                        ],
                      ),
                      // 🔥 显示最后一条消息内容（微信式）
                      if (item.formattedSubtitle.isNotEmpty) ...[
                        const SizedBox(height: 4),
                        Row(
                          children: [
                            Expanded(
                              child: Text(
                                item.formattedSubtitle,
                                style: TextStyle(
                                  fontSize: 13,
                                  color: Colors.grey[600],
                                  fontWeight: FontWeight.normal,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ],
                  ),
                ),
                
                const SizedBox(width: 8),
                
                // 🎨 箭头图标
                Container(
                  padding: const EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: const Color(0xFFF8F9FA),
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: Icon(
                    Icons.chevron_right,
                    color: Colors.grey[400],
                    size: 20,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
  
  /// 构建好友列表 Tab（原来的，现在不用了，但保留代码以备后用）
  Widget _buildFriendListTab() {
    return Obx(() {
      // 加载状态
      if (controller.isLoading.value && controller.friendList.isEmpty) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      // 错误状态
      if (controller.hasError.value && controller.friendList.isEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.error_outline,
                size: 64,
                color: Colors.grey[400],
              ),
              const SizedBox(height: 16),
              Text(
                controller.errorMessage.value,
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 16,
                ),
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: controller.refreshFriendList,
                child: const Text('重试'),
              ),
            ],
          ),
        );
      }
      
      // ✅ 修复：空状态也支持下拉刷新
      if (controller.friendList.isEmpty) {
        return RefreshIndicator(
          onRefresh: controller.refreshFriendList,
          child: ListView(
            physics: const AlwaysScrollableScrollPhysics(),
            children: [
              SizedBox(
                height: MediaQuery.of(Get.context!).size.height * 0.6,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.people_outline,
                        size: 64,
                        color: Colors.grey[400],
                      ),
                      const SizedBox(height: 16),
                      Text(
                        '暂无好友',
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 16,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '下拉可刷新好友列表',
                        style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      }
      
      // 🎨 好友列表（卡片式布局，移除分割线）
      return RefreshIndicator(
        onRefresh: controller.refreshFriendList,
        child: ListView.builder(
          padding: const EdgeInsets.symmetric(vertical: 4),
          itemCount: controller.friendList.length,
          itemBuilder: (context, index) {
            final friend = controller.friendList[index];
            return _buildFriendItem(friend);
          },
        ),
      );
    });
  }
  
  /// 构建好友申请列表 Tab（🔥 分组显示：待处理 + 已处理）
  Widget _buildFriendRequestListTab() {
    return Obx(() {
      // 加载状态
      if (controller.isLoadingRequests.value && 
          controller.pendingFriendRequests.isEmpty &&
          controller.processedFriendRequests.isEmpty) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      // 空状态
      if (controller.pendingFriendRequests.isEmpty &&
          controller.processedFriendRequests.isEmpty) {
        return RefreshIndicator(
          onRefresh: controller.refreshFriendRequestList,
          child: ListView(
            physics: const AlwaysScrollableScrollPhysics(),
            children: [
              SizedBox(
                height: MediaQuery.of(Get.context!).size.height * 0.6,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.person_add_alt_1_outlined,
                        size: 64,
                        color: Colors.grey[400],
                      ),
                      const SizedBox(height: 16),
                      Text(
                        '暂无好友申请',
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 16,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '下拉可刷新好友申请',
                        style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      }
      
      // 🎨 好友申请列表（分组显示：待处理 + 已处理）
      return RefreshIndicator(
        onRefresh: controller.refreshFriendRequestList,
        child: ListView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(vertical: 4),
          children: [
            // 🔥 待处理申请
            if (controller.pendingFriendRequests.isNotEmpty)
              _buildFriendRequestSection(
                title: '待处理',
                count: controller.pendingFriendRequests.length,
                requests: controller.pendingFriendRequests,
                isPending: true,
              ),
            
            // 🔥 已处理申请
            if (controller.processedFriendRequests.isNotEmpty)
              _buildFriendRequestSection(
                title: '已处理',
                count: controller.processedFriendRequests.length,
                requests: controller.processedFriendRequests,
                isPending: false,
              ),
          ],
        ),
      );
    });
  }
  
  /// 🎨 构建好友申请区域（分组）
  Widget _buildFriendRequestSection({
    required String title,
    required int count,
    required List<FriendRequestEntity> requests,
    required bool isPending,
  }) {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),
      padding: const EdgeInsets.all(12.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(5),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: isPending
                        ? [const Color(0xFFFF6B6B), const Color(0xFFD84545)]
                        : [const Color(0xFF9E9E9E), const Color(0xFF757575)],
                  ),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  isPending ? Icons.pending_actions : Icons.history,
                  color: Colors.white,
                  size: 14,
                ),
              ),
              const SizedBox(width: 6),
              Text(
                '$title ($count)',
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF333333),
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          ...requests.map((request) => Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: _buildFriendRequestItem(request),
          )),
        ],
      ),
    );
  }
  
  /// 🎨 构建好友列表项（现代化卡片式设计）
  Widget _buildFriendItem(friend) {
    return Dismissible(
      key: Key('friend_${friend.friendId}'),
      direction: DismissDirection.endToStart,
      confirmDismiss: (direction) async {
        return await Get.dialog<bool>(
          AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            title: const Text('确认删除'),
            content: Text('确定要删除好友"${friend.displayName}"吗？'),
            actions: [
              TextButton(
                onPressed: () => Get.back(result: false),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () => Get.back(result: true),
                style: TextButton.styleFrom(foregroundColor: const Color(0xFFD84545)),
                child: const Text('删除'),
              ),
            ],
          ),
        );
      },
      onDismissed: (direction) {
        controller.deleteFriend(friend);
      },
      background: Container(
        margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),
        decoration: BoxDecoration(
          gradient: const LinearGradient(
            colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
          ),
          borderRadius: BorderRadius.circular(12),
        ),
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 20),
        child: const Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.delete_outline, color: Colors.white, size: 24),
            SizedBox(height: 4),
            Text(
              '删除',
              style: TextStyle(
                color: Colors.white,
                fontSize: 12,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      ),
      child: Container(
        margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.04),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: () => controller.onFriendTap(friend),
            borderRadius: BorderRadius.circular(12),
            child: Padding(
              padding: const EdgeInsets.all(12.0),
              child: Row(
                children: [
                  // 🎨 头像（带渐变阴影 + 点击跳转）
                  GestureDetector(
                    onTap: () => controller.onAvatarTap(friend.friendId),
                    child: Container(
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(
                            color: const Color(0xFFD84545).withOpacity(0.2),
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: CircleAvatar(
                        radius: 28,
                        backgroundColor: Colors.grey[200],
                        backgroundImage: friend.avatarUrl.isNotEmpty 
                            ? CachedNetworkImageProvider(friend.avatarUrl)
                            : null,
                        child: friend.avatarUrl.isEmpty 
                            ? Icon(Icons.person, size: 32, color: Colors.grey[400])
                            : null,
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  
                  // 🎨 信息区域
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 昵称 + 性别图标
                        Row(
                          children: [
                            Flexible(
                              child: Text(
                                friend.displayName,
                                style: const TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600,
                                  color: Color(0xFF333333),
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            if (friend.userGender != null) ...[
                              const SizedBox(width: 6),
                              // 🎨 性别图标（圆形渐变背景）
                              Container(
                                width: 18,
                                height: 18,
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  gradient: LinearGradient(
                                    colors: friend.userGender == '女'
                                        ? [const Color(0xFFFF6B9D), const Color(0xFFC94B84)]
                                        : [const Color(0xFF4FC3F7), const Color(0xFF29B6F6)],
                                  ),
                                ),
                                child: Icon(
                                  friend.userGender == '女' ? Icons.female : Icons.male,
                                  size: 12,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ],
                        ),
                        // 签名
                        if (friend.userSignature != null && friend.userSignature!.isNotEmpty)
                          Padding(
                            padding: const EdgeInsets.only(top: 4),
                            child: Text(
                              friend.userSignature!,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                fontSize: 13,
                                color: Colors.grey[600],
                                height: 1.2,
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),
                  
                  const SizedBox(width: 8),
                  
                  // 🎨 箭头图标
                  Container(
                    padding: const EdgeInsets.all(4),
                    decoration: BoxDecoration(
                      color: const Color(0xFFF8F9FA),
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Icon(
                      Icons.chevron_right,
                      color: Colors.grey[400],
                      size: 20,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
  
  /// 🎨 构建好友申请列表项（现代化卡片式设计）
  Widget _buildFriendRequestItem(request) {
    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: const Color(0xFFF8F9FA),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
          children: [
            // 🎨 头像（带渐变阴影 + 点击跳转）
            GestureDetector(
              onTap: () => controller.onRequestAvatarTap(request.senderId),
              child: Container(
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0xFFFF6B6B).withOpacity(0.2),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: CircleAvatar(
                  radius: 28,
                  backgroundColor: Colors.grey[200],
                  backgroundImage: request.avatarUrl.isNotEmpty 
                      ? CachedNetworkImageProvider(request.avatarUrl)
                      : null,
                  child: request.avatarUrl.isEmpty 
                      ? Icon(Icons.person, size: 32, color: Colors.grey[400])
                      : null,
                ),
              ),
            ),
            const SizedBox(width: 12),
            
            // 🎨 信息区域
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 昵称 + 性别图标
                  Row(
                    children: [
                      Flexible(
                        child: Text(
                          request.displayName,
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: Color(0xFF333333),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      if (request.senderGender != null) ...[
                        const SizedBox(width: 6),
                        // 🎨 性别图标（圆形渐变背景）
                        Container(
                          width: 18,
                          height: 18,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            gradient: LinearGradient(
                              colors: request.senderGender == '女'
                                  ? [const Color(0xFFFF6B9D), const Color(0xFFC94B84)]
                                  : [const Color(0xFF4FC3F7), const Color(0xFF29B6F6)],
                            ),
                          ),
                          child: Icon(
                            request.senderGender == '女' ? Icons.female : Icons.male,
                            size: 12,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ],
                  ),
                  // 申请消息
                  if (request.message != null && request.message!.isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.only(top: 4),
                      child: Text(
                        request.message!,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey[600],
                          height: 1.2,
                        ),
                      ),
                    ),
                ],
              ),
            ),
            
            const SizedBox(width: 8),
            
            // 🎨 操作按钮（待处理状态显示同意/拒绝按钮）
            if (request.isPending)
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 拒绝按钮
                  Material(
                    color: Colors.transparent,
                    child: InkWell(
                      onTap: () => controller.handleFriendRequest(request, 'reject'),
                      borderRadius: BorderRadius.circular(10),
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(10),
                          border: Border.all(
                            color: const Color(0xFFE0E0E0),
                            width: 1,
                          ),
                        ),
                        child: const Text(
                          '拒绝',
                          style: TextStyle(
                            color: Color(0xFF666666),
                            fontSize: 12,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  // 同意按钮（渐变背景 + 阴影）
                  Container(
                    decoration: BoxDecoration(
                      gradient: const LinearGradient(
                        colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                      ),
                      borderRadius: BorderRadius.circular(10),
                      boxShadow: [
                        BoxShadow(
                          color: const Color(0xFFD84545).withOpacity(0.2),
                          blurRadius: 4,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        onTap: () => controller.handleFriendRequest(request, 'accept'),
                        borderRadius: BorderRadius.circular(10),
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                          child: const Text(
                            '同意',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              )
            else
              // 已处理状态标签
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: request.statusText == '已同意'
                        ? [const Color(0xFF66BB6A), const Color(0xFF4CAF50)]
                        : [const Color(0xFF9E9E9E), const Color(0xFF757575)],
                  ),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  request.statusText,
                  style: const TextStyle(
                    fontSize: 11,
                    color: Colors.white,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
          ],
      ),
    );
  }
  
  // ==================== 活动申请标签页 ====================
  
  /// 🔥 构建活动申请列表 Tab
  Widget _buildActivityApplicationListTab() {
    return Obx(() {
      // 加载状态
      if (controller.isLoadingActivityApplications.value && 
          controller.pendingActivityApplications.isEmpty &&
          controller.processedActivityApplications.isEmpty) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      // 空状态
      if (controller.pendingActivityApplications.isEmpty &&
          controller.processedActivityApplications.isEmpty) {
        return RefreshIndicator(
          onRefresh: controller.refreshActivityApplications,
          child: ListView(
            physics: const AlwaysScrollableScrollPhysics(),
            children: [
              SizedBox(
                height: MediaQuery.of(Get.context!).size.height * 0.6,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.inbox_outlined,
                        size: 64,
                        color: Colors.grey[400],
                      ),
                      const SizedBox(height: 16),
                      Text(
                        '暂无活动申请',
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 16,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '下拉可刷新活动申请',
                        style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      }
      
      // 🎨 活动申请列表
      return RefreshIndicator(
        onRefresh: controller.refreshActivityApplications,
        child: ListView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(vertical: 4),
          children: [
            // 待审核申请
            if (controller.pendingActivityApplications.isNotEmpty)
              _buildActivityApplicationSection(
                title: '待审核',
                count: controller.pendingActivityApplications.length,
                applications: controller.pendingActivityApplications,
                isPending: true,
              ),
            
            // 已处理申请
            if (controller.processedActivityApplications.isNotEmpty)
              _buildActivityApplicationSection(
                title: '已处理',
                count: controller.processedActivityApplications.length,
                applications: controller.processedActivityApplications,
                isPending: false,
              ),
          ],
        ),
      );
    });
  }
  
  /// 🎨 构建活动申请区域
  Widget _buildActivityApplicationSection({
    required String title,
    required int count,
    required List applications,
    required bool isPending,
  }) {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),
      padding: const EdgeInsets.all(12.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(5),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: isPending
                        ? [const Color(0xFFFF9800), const Color(0xFFF57C00)]
                        : [const Color(0xFF9E9E9E), const Color(0xFF757575)],
                  ),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  isPending ? Icons.pending_actions : Icons.history,
                  color: Colors.white,
                  size: 14,
                ),
              ),
              const SizedBox(width: 6),
              Text(
                '$title ($count)',
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF333333),
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          ...applications.map((app) => _buildActivityApplicationCard(app, isPending: isPending)),
        ],
      ),
    );
  }
  
  /// 🎨 构建活动申请卡片
  Widget _buildActivityApplicationCard(application, {required bool isPending}) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: const Color(0xFFF8F9FA),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户信息
          Row(
            children: [
              // 头像
              GestureDetector(
                onTap: () => controller.onActivityApplicationAvatarTap(application.userId),
                child: CachedAvatar(
                  avatarUrl: application.userAvatarUrl?.isNotEmpty == true
                      ? application.userAvatarUrl!
                      : 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_16.webp',
                  size: 50,
                  placeholderIcon: Icons.person,
                ),
              ),
              const SizedBox(width: 12),
              
              // 用户信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        // 用户名
                        Text(
                          application.userName,
                          style: const TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.w600,
                            color: Color(0xFF333333),
                          ),
                        ),
                        const SizedBox(width: 6),
                        
                        // 性别图标
                        if (application.userGender?.isNotEmpty == true)
                          Container(
                            width: 18,
                            height: 18,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              gradient: LinearGradient(
                                colors: application.userGender == '男'
                                    ? [const Color(0xFF4FC3F7), const Color(0xFF29B6F6)]
                                    : [const Color(0xFFFF6B9D), const Color(0xFFC94B84)],
                              ),
                            ),
                            child: Icon(
                              application.userGender == '男' ? Icons.male : Icons.female,
                              color: Colors.white,
                              size: 12,
                            ),
                          ),
                        const SizedBox(width: 6),
                        
                        // 年龄标签
                        if (application.userAge != null)
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                            decoration: BoxDecoration(
                              color: application.userGender == '男'
                                  ? const Color(0xFF4FC3F7).withOpacity(0.1)
                                  : const Color(0xFFFF6B9D).withOpacity(0.1),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              '${application.userAge}岁',
                              style: TextStyle(
                                fontSize: 11,
                                fontWeight: FontWeight.w600,
                                color: application.userGender == '男'
                                    ? const Color(0xFF29B6F6)
                                    : const Color(0xFFC94B84),
                              ),
                            ),
                          ),
                        const SizedBox(width: 6),
                        
                        // 等级标签
                        if (application.userLevel != null)
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                            decoration: BoxDecoration(
                              gradient: const LinearGradient(
                                colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                              ),
                              borderRadius: BorderRadius.circular(8),
                              boxShadow: [
                                BoxShadow(
                                  color: const Color(0xFFD84545).withOpacity(0.2),
                                  blurRadius: 4,
                                  offset: const Offset(0, 2),
                                ),
                              ],
                            ),
                            child: Text(
                              LevelUtil.getLevelNameFromPoints(application.userLevel!),
                              style: const TextStyle(
                                fontSize: 10,
                                fontWeight: FontWeight.w600,
                                color: Colors.white,
                              ),
                            ),
                          ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    if (application.userSignature?.isNotEmpty == true)
                      Text(
                        application.userSignature!,
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xFF999999),
                          fontWeight: FontWeight.w500,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                  ],
                ),
              ),
              
              // 状态标签
              if (!isPending)
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: application.isApproved
                          ? [const Color(0xFF66BB6A), const Color(0xFF4CAF50)]
                          : [const Color(0xFFFF6B6B), const Color(0xFFD84545)],
                    ),
                    borderRadius: BorderRadius.circular(10),
                    boxShadow: [
                      BoxShadow(
                        color: (application.isApproved
                            ? const Color(0xFF4CAF50)
                            : const Color(0xFFD84545)).withOpacity(0.2),
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Text(
                    application.isApproved ? '已通过' : '已拒绝',
                    style: const TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                  ),
                ),
            ],
          ),
          
          // 活动信息
          const SizedBox(height: 10),
          Container(
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(4),
                      decoration: BoxDecoration(
                        color: const Color(0xFF4FC3F7).withOpacity(0.1),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: const Icon(
                        Icons.event_rounded,
                        color: Color(0xFF4FC3F7),
                        size: 14,
                      ),
                    ),
                    const SizedBox(width: 6),
                    Expanded(
                      child: Text(
                        application.activityName,
                        style: const TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                          color: Color(0xFF333333),
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 6),
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(4),
                      decoration: BoxDecoration(
                        color: const Color(0xFF9E9E9E).withOpacity(0.1),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: const Icon(
                        Icons.access_time_rounded,
                        color: Color(0xFF9E9E9E),
                        size: 14,
                      ),
                    ),
                    const SizedBox(width: 6),
                    Text(
                      '申请时间: ${application.applicationTime}',
                      style: const TextStyle(
                        fontSize: 12,
                        color: Color(0xFF999999),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          
          // 操作按钮（仅待审核显示）
          if (isPending) ...[
            const SizedBox(height: 10),
            Row(
              children: [
                // 拒绝按钮
                Expanded(
                  child: Container(
                    height: 38,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border.all(
                        color: const Color(0xFFE0E0E0),
                        width: 1.5,
                      ),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: ElevatedButton.icon(
                      onPressed: () => _showRejectActivityDialog(application),
                      icon: const Icon(Icons.close, size: 16),
                      label: const Text(
                        '拒绝',
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.transparent,
                        foregroundColor: const Color(0xFFFF6B6B),
                        shadowColor: Colors.transparent,
                        elevation: 0,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 10),
                // 通过按钮
                Expanded(
                  child: Container(
                    height: 38,
                    decoration: BoxDecoration(
                      gradient: const LinearGradient(
                        colors: [Color(0xFF66BB6A), Color(0xFF4CAF50)],
                      ),
                      borderRadius: BorderRadius.circular(10),
                      boxShadow: [
                        BoxShadow(
                          color: const Color(0xFF4CAF50).withOpacity(0.3),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: ElevatedButton.icon(
                      onPressed: () => _showApproveActivityDialog(application),
                      icon: const Icon(Icons.check, size: 16),
                      label: const Text(
                        '通过',
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.transparent,
                        foregroundColor: Colors.white,
                        shadowColor: Colors.transparent,
                        elevation: 0,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ],
      ),
    );
  }
  
  /// 显示通过活动申请对话框
  void _showApproveActivityDialog(application) {
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        child: Container(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [Color(0xFF66BB6A), Color(0xFF4CAF50)],
                  ),
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0xFF4CAF50).withOpacity(0.3),
                      blurRadius: 10,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: const Icon(
                  Icons.check_circle_rounded,
                  color: Colors.white,
                  size: 30,
                ),
              ),
              const SizedBox(height: 16),
              const Text(
                '通过申请',
                style: TextStyle(
                  fontSize: 17,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF333333),
                ),
              ),
              const SizedBox(height: 8),
              Text(
                '确定通过「${application.userName}」的活动申请吗？',
                style: const TextStyle(
                  fontSize: 13,
                  color: Color(0xFF666666),
                  fontWeight: FontWeight.w500,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 20),
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () => Get.back(),
                      child: const Text('取消'),
                    ),
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Container(
                      height: 42,
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(
                          colors: [Color(0xFF66BB6A), Color(0xFF4CAF50)],
                        ),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: ElevatedButton(
                        onPressed: () async {
                          Get.back();
                          await controller.approveActivityApplication(application);
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.transparent,
                          shadowColor: Colors.transparent,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                        child: const Text('确定通过'),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
  
  /// 显示拒绝活动申请对话框
  void _showRejectActivityDialog(application) {
    final TextEditingController noteController = TextEditingController();
    
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        child: Container(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                  ),
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0xFFD84545).withOpacity(0.3),
                      blurRadius: 10,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: const Icon(
                  Icons.cancel_rounded,
                  color: Colors.white,
                  size: 30,
                ),
              ),
              const SizedBox(height: 16),
              const Text(
                '拒绝申请',
                style: TextStyle(
                  fontSize: 17,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF333333),
                ),
              ),
              const SizedBox(height: 8),
              Text(
                '确定拒绝「${application.userName}」的活动申请吗？',
                style: const TextStyle(
                  fontSize: 13,
                  color: Color(0xFF666666),
                  fontWeight: FontWeight.w500,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              TextField(
                controller: noteController,
                decoration: InputDecoration(
                  hintText: '可选：填写拒绝原因',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                  contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                ),
                maxLines: 3,
              ),
              const SizedBox(height: 20),
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () => Get.back(),
                      child: const Text('取消'),
                    ),
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Container(
                      height: 42,
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(
                          colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                        ),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: ElevatedButton(
                        onPressed: () async {
                          final note = noteController.text.trim();
                          Get.back();
                          await controller.rejectActivityApplication(
                            application,
                            note: note.isNotEmpty ? note : null,
                          );
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.transparent,
                          shadowColor: Colors.transparent,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                        child: const Text('确定拒绝'),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MessageIndexController>(
      init: MessageIndexController(),
      id: "message_index",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFF8F9FA),
          appBar: AppBar(
            leading: IconButton(
              onPressed: () => Get.back(),
              icon: const Icon(Icons.arrow_back_ios_new_outlined),
            ),
            title: Obx(() {
              final count = controller.totalMessageCount;
              return Text(
                '我的消息${count > 0 ? controller.formatMessageCount(count) : ''}',
                style: const TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF333333),
                ),
              );
            }),
            backgroundColor: Colors.white,
            elevation: 0,
            centerTitle: true,
          ),
          body: _buildView(),
        );
      },
    );
  }
}
